import { Message } from "element-ui";
import { stsDispatcherAPI } from "@/api/km_oss";

export default {
    namespaced: true,
    state: {
        stsCache: null,
        Expiration: 0,
    },
    mutations: {
        SAVE_STS: (state, data) => {
            state.stsCache = data;
        },
        SAVE_Expiration: (state, data) => {
            state.Expiration = data;
        },
    },
    actions: {
        async stsDispatcherAction({ state, commit }) {
            const { Expiration } = state;

            // 这里加3秒的意思是,在过期前3秒就可以这个临时密钥就可以当做已经失效了
            if (Expiration && Date.now() + 3000 < new Date(Expiration).getTime()) {
                return false;
            }
            try {
                const { data } = await stsDispatcherAPI();

                const formatData = data.str
                    .split("")
                    .reverse()
                    .join("")
                    .split(".");

                const STS = {
                    AccessKeyId: `STS.${formatData[0]}`,
                    AccessKeySecret: formatData[1],
                    SecurityToken: `${formatData[2]}==`,
                };

                commit("SAVE_STS", STS);
                commit("SAVE_Expiration", data.Expiration);

                return true;
            } catch (error) {
                Message.error("网络错误");
                return false;
            }
        },
    },
};
